﻿var ERR_NET_ERR_PROXY_CONNECTION_FAILED = 1;
var ERR_NET_ERR_ABORTED = 2;
var ERR_NET_ERR_TUNNEL_CONNECTION_FAILED = 3;
var ERR_NET_ERR_CONNECTION_TIMED_OUT = 4;
var ERR_NET_ERR_ERR_BLOCKED_BY_CLIENT = 11; // may be cancel in onBeforeRequest
var ERR_UNKNOWN = 128;

function sprintf(fmt) {
	var args = arguments;
	var idx = 0;
	// notice, the $2 isn't the str matched
	return fmt.replace(/%[a-z]/g, function(match, index, regex) { 
		idx++;
		return (typeof args[idx] != 'undefined') ? args[idx] : match;
	});
}

function time_to_str(date) {
	return (date instanceof Date) ?
			sprintf("%h:%m:%s", date.getHours(), date.getMinutes(), date.getSeconds()) :
			undefined;
}

function regexMapGet(map, key) {
	var regex;
	for (var i = 0; i < map.length; i++) {
		regex = new RegExp(map[i][0]);
		if (regex.test(key)) {
			return map[i][1];
		}
	}
	return null;
}

function getErrCode(error) {
	var map = new Array(
		new Array("net::ERR_PROXY_CONNECTION_FAILED", ERR_NET_ERR_PROXY_CONNECTION_FAILED),
		new Array("net::ERR_ABORTED", ERR_NET_ERR_ABORTED),
		new Array("net::ERR_TUNNEL_CONNECTION_FAILED", ERR_NET_ERR_TUNNEL_CONNECTION_FAILED),
		new Array("net::ERR_CONNECTION_TIMED_OUT", ERR_NET_ERR_CONNECTION_TIMED_OUT),
		new Array("net::ERR_BLOCKED_BY_CLIENT", ERR_NET_ERR_ERR_BLOCKED_BY_CLIENT)
	);
	var errno = regexMapGet(map, error);
	if (errno) {
		return errno;
	}
	
	return ERR_UNKNOWN;
}
